package br.nextfm.dao;

import java.util.List;

import javax.persistence.Query;

import br.nextfm.model.Comentario;

public class ComentarioDao extends Dao {
	
	public boolean insert(Comentario comentario) {

		try {

			getManager().getTransaction().begin();
			getManager().persist(comentario);
			getManager().getTransaction().commit();

			return true;

		} 

		catch (Exception e) {

			e.printStackTrace();

			return false;
		}
		
	}
	
	public boolean update(Comentario comentario) {
		
		try {

			getManager().getTransaction().begin();
			getManager().merge(comentario);
			getManager().getTransaction().commit();

			return true;

		} 

		catch (Exception e) {

			e.printStackTrace();

			return false;
		}
		
	}
	
	public boolean delete(int id) {
		
		try {

			getManager().getTransaction().begin();
			Comentario comentario = getManager().find(Comentario.class, id);
			getManager().remove(comentario);
			getManager().getTransaction().commit();

			return true;

		} 

		catch (Exception e) {

			e.printStackTrace();

			return false;
		}
		
	}
	
	public Comentario get(int id) {

		try {

			return getManager().find(Comentario.class, id);

		} 

		catch (Exception e) {

			e.printStackTrace();

			return null;

		}
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Comentario> getAll() {
		
		try {

			getManager().getTransaction().begin();
			Query query = getManager().createQuery("SELECT c FROM Comentario c ORDER BY a.nome");

			return query.getResultList();

		}

		catch (Exception e) {

			e.printStackTrace();

			return null;

		}
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Comentario> getTop() {
		
		try {

			getManager().getTransaction().begin();
			Query query = getManager().createQuery("SELECT c FROM Comentario c ORDER BY c.id DESC");

			return  query.setMaxResults(3).getResultList();

		}

		catch (Exception e) {

			e.printStackTrace();

			return null;

		}
		
	}

}
